package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Student on 25.08.2014.
 */

public class EmailService {

    public EmailService() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                queue.remove();
            }
        }).start();
    }

    private static Queue queue = new Queue();

    public static void sendNotificationEmail(Email email) {

    }

    public static void close() {
        queue.isClose = true;
    }


    static class Queue {
        private static List<Email> list = new LinkedList<Email>();
        private Object addLock;
        private Object removeLock;
        private boolean isClose;

        public void add(Email email) {
            if (isClose) {
                removeLock.notifyAll();
                return;
            }
            synchronized (addLock) {
                list.add(email);
                removeLock.notify();
            }
        }

        public void remove() {

            synchronized (removeLock) {
                try {
                    while (list.isEmpty() /*&& !isClose*/) removeLock.wait();
                } catch (InterruptedException e) {
                }
                if (!list.isEmpty())
                    list.remove(0);
            }

        }
    }
}
